package com.shop.config.timer;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shop.common.BeanUtil;
import com.shop.config.timer.impl.DataContainerImpl;
import com.shop.entity.SystemParameterDo;
import com.shop.mapper.SystemParameterDoMapper;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

@Slf4j
@Component
public class TimedTaskConfig {

    /**
     * 执行任务触发器
     *
     * @throws Exception
     */
    @PostConstruct
    public void startTask() throws Exception {
        //1、创建调度器
        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        Scheduler scheduler = schedulerFactory.getScheduler();
        this.startGetDataSource(scheduler);
        scheduler.start();
    }

    /**
     * 创建获取数据源任务
     *
     * @throws Exception
     */
    private void startGetDataSource(Scheduler scheduler) throws Exception {
        // 1、创建任务实例
        JobKey key = new JobKey("DataSource", "getDataSources");
        if (!scheduler.checkExists(key)) return;
        JobDetail jobDetail = JobBuilder.newJob(DataContainerImpl.class)
                .withIdentity("DataSource", "getDataSources").build();

        // 2、触发设置时间
        CronScheduleBuilder builder = CronScheduleBuilder.cronSchedule(this.getTestTingTime());
        // 3、构建触发器实例
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("DataSourceTrigger", "DataSourceGroupTrigger").startNow()
                .withSchedule(builder)
                .build();
        scheduler.scheduleJob(jobDetail, trigger);

        log.info("-------- 获取数据源定时器启动 ! ------------");
        scheduler.start();
    }

    /**
     * 获取定时检测时间
     *
     * @return
     */
    private String getTestTingTime() {
        String testting = "*/10 * * * * ?";
        try {
            SystemParameterDoMapper systemArgumentService = BeanUtil.getBeanByBeanName("systemParameterDoMapper", SystemParameterDoMapper.class);
            QueryWrapper<SystemParameterDo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("system_type",40000L);
            testting = systemArgumentService.selectList(queryWrapper).get(0).getSystemValue();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return testting;
    }

}
